package vip.xiaonuo.modular.front.bloginfo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.modular.blogcomment.entity.BlogComment;
import vip.xiaonuo.modular.blogcomment.service.BlogCommentService;
import vip.xiaonuo.modular.bloginfo.entity.BlogInfo;
import vip.xiaonuo.modular.bloginfo.param.BlogInfoParam;
import vip.xiaonuo.modular.bloginfo.service.BlogInfoService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liu
 */
@RestController
@RequestMapping("/front/blogInfo")
public class FrontBlogInfoController {

    @Resource
    private BlogInfoService blogInfoService;

    @Resource
    private BlogCommentService blogCommentService;

    @GetMapping("/page")
    public ResponseData pubPage(BlogInfoParam blogInfoParam) {
        PageResult<BlogInfo> page = blogInfoService.pubPage(blogInfoParam);
        List<BlogInfo> list = page.getRows();
        QueryWrapper<BlogComment> wrapper = new QueryWrapper<>();
        for (int i = 0; i < list.size(); i++) {
            wrapper.lambda().eq(BlogComment::getBlogId, list.get(i).getBlogId());
            BlogInfo info = list.get(i);
            info.setCommentCount(blogCommentService.count(wrapper));
            info.setBlogViews(blogInfoService.getById(list.get(i).getBlogId()).getBlogViews());
            wrapper.clear();
            list.set(i, info);
        }
        page.setRows(list);
        return new SuccessResponseData(page);
    }

    @GetMapping("/article/{blogId}")
    public ResponseData list(@PathVariable("blogId") String blogId) {
        BlogInfo info = blogInfoService.getOne(blogId, true);
        if (!StringUtils.isNumeric(blogId)) {
            return ResponseData.error("对不起，文章ID只能为数字");
        }
        if (info==null) {
            return ResponseData.error("对不起，未找到该文章");
        }
        info.setBlogViews(blogInfoService.getById(Long.parseLong(blogId)).getBlogViews());
        return new SuccessResponseData(info);
    }

    @GetMapping("/view/{blogId}")
    public void view(@PathVariable("blogId") String blogId) {
        blogInfoService.view(blogId);
    }
}
